package com.feidian.helper.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.DynamicLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.feidian.helper.R;
import com.feidian.helper.bean.Table;
import com.feidian.helper.bean.User;
import com.feidian.helper.net.NetManager;
import com.feidian.helper.ui.fragment.AcceptFragment;
import com.feidian.helper.ui.fragment.SendFragment;
import com.feidian.helper.util.Constant;
import com.feidian.helper.util.Utils;

public class LoginActivity extends Activity implements OnClickListener {
	private static final int GET_CONTENT_SUCCESS = 0X123;
	private static final int GET_CONTENT_FAILURE = 0X124;

	private static final int DOWNLOAD_SUCCESS = 0X125;
	private static final int DOWNLOAD_FAILURE = 0X126;

	private Button register;
	private TextView mForget;
	private Button login;
	private CheckBox remember;

	private EditText username_edit;
	private EditText password_edit;

	private SharedPreferences sp;
	private String headName;
	private Dialog processDialog;
	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case GET_CONTENT_SUCCESS: {
				// Toast.makeText(LoginActivity.this,
				// (String)msg.obj+"",Toast.LENGTH_LONG).show();\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
				Map<String, String> map = parseJSONString((String) msg.obj);
				if (map.get(Table.stuId) == null || map.get(Table.name) == null
						|| map.get(Table.password) == null) {
					//User.isLogin = false;
					
					Toast.makeText(LoginActivity.this, "用户名或密码错误",
							Toast.LENGTH_SHORT).show();
					break;
				}
				User.stuId = map.get(Table.stuId);
				User.name = map.get(Table.name);
				User.password = map.get(Table.password);
				User.sex = map.get(Table.sex);
				User.qq = map.get(Table.qq);
				User.phone = map.get(Table.phone);
				User.sendStart = map.get(Table.sendStart);
				User.acceptStart = map.get(Table.acceptStart);
				User.ImgUrl = map.get(Table.ImgUrl);
				
				//User.isLogin = true;
				Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_SHORT)
						.show();
				
				User.originPassword = map.get(Table.originPassword);
				
				Editor edit = sp.edit();
				edit.putString(Table.name, User.name);
				edit.putString(Table.stuId, User.stuId);
				edit.putString(Table.password, User.password);
				edit.putString(Table.phone, User.phone);
				edit.putString(Table.sex, User.sex);
				edit.putString(Table.qq, User.qq);
				edit.putString(Table.sendStart, User.sendStart);
				edit.putString(Table.acceptStart, User.acceptStart);
				edit.putString(Table.ImgUrl, User.ImgUrl);
				edit.putBoolean(Table.isLogin, true);
				edit.commit();
				Log.e("edit.commit()", "success");
				AcceptFragment.accept_tag.setText("下拉以刷新");
				SendFragment.send_tag.setText("下拉以刷新");
				if (User.ImgUrl != null && !User.ImgUrl.equals("null")
						&& !User.ImgUrl.equals("")) {
					Thread downLoadThread = new DownLoadThread(User.ImgUrl);
					downLoadThread.start();
				}
				else{
					User.head=null;
					SharedPreferences sp = getSharedPreferences(
							Table.CommentUserInf, Context.MODE_PRIVATE);
					Editor editor = sp.edit();
					editor.putString(Table.headHeadImageName,
							"-1");
					editor.commit();
					processDialog.dismiss();
					startActivity(new Intent(LoginActivity.this,
							MainFragmentActivity.class));
				}

			}
				break;
			case GET_CONTENT_FAILURE: {
				processDialog.dismiss();
				sp.edit().putBoolean(Table.isLogin, false).commit();
				Toast.makeText(LoginActivity.this, "出错了", Toast.LENGTH_LONG)
						.show();
			}
				break;
			case DOWNLOAD_SUCCESS: {
				processDialog.dismiss();
				startActivity(new Intent(LoginActivity.this,
						MainFragmentActivity.class));
			}
				break;
			case DOWNLOAD_FAILURE: {
				processDialog.dismiss();
			}
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// getWindow().setFlags(WindowManager.LayoutParams.FILL_PARENT,
		// WindowManager.LayoutParams.FILL_PARENT);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_login);
		initView();
	}

	private void initView() {

		sp = this.getSharedPreferences(Table.CommentUserInf,
				Context.MODE_PRIVATE);

		username_edit = (EditText) findViewById(R.id.username_edit);
		password_edit = (EditText) findViewById(R.id.password_edit);

		register = (Button) findViewById(R.id.register_link);
		register.setOnClickListener(this);

		mForget = (TextView) findViewById(R.id.forget_link);
		mForget.setOnClickListener(this);

		login = (Button) findViewById(R.id.signin_button);
		login.setOnClickListener(this);

		remember = (CheckBox) findViewById(R.id.chk_remember);
		remember.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				remember.setChecked(isChecked);
				sp.edit().putBoolean(Constant.ISCHECK, isChecked).commit();
			}
		});

		// initData();
	}

	private void initData() {
		boolean checked = sp.getBoolean(Constant.ISCHECK, false);

		if (checked) {
			password_edit.setText(sp.getString(Constant.USER_PASSWORD, ""));
		} else {
			password_edit.setText("");
		}
		username_edit.setText(sp.getString(Constant.USER_NAME, ""));
		remember.setChecked(checked);
	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch (id) {
		case R.id.register_link:
			startActivity(new Intent(this, RegisterActivity.class));
			break;
		case R.id.forget_link:
			startActivity(new Intent(this, ResetPasswordActivity.class));
			break;
		case R.id.signin_button: {
			/*
			 * if (remember.isChecked()) { Editor editor = sp.edit();
			 * editor.putString(Constant.USER_NAME, username_edit.getText()
			 * .toString().trim()); editor.putString(Constant.USER_PASSWORD,
			 * password_edit .getText().toString().trim()); editor.commit(); }
			 */
			/*
			 * startActivity(new Intent(LoginActivity.this,
			 * MainFragmentActivity.class));
			 */
			if (password_edit.getText().toString().equals("")) {
				Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_LONG)
						.show();
				return;
			}
			if (username_edit.getText().toString().equals("")) {
				Toast.makeText(LoginActivity.this, "用户名不能为空", Toast.LENGTH_LONG)
						.show();
				return;
			}
			String url = "http://115.29.103.105/User/Login";
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(Table.id, username_edit.getText()
					.toString()));
			params.add(new BasicNameValuePair(Table.password, password_edit
					.getText().toString()));
			LoginThread loginThread = new LoginThread(url, params);
			loginThread.start();
			/*
			 * 正在登陆Dialog
			 * */
			LayoutInflater inflater = LayoutInflater.from(this);
			View v = inflater.inflate(R.layout.dialogview, null);

			LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);

			ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
			Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this,
					R.anim.animation);
			spaceshipImage.startAnimation(hyperspaceJumpAnimation);
			TextView textView=(TextView)v.findViewById(R.id.content);
			textView.setText("正在登陆。。。。。");
			processDialog= new Dialog(LoginActivity.this,
					R.style.NoTitleDialog);
			processDialog.setCancelable(true);
			processDialog.show();
			processDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT));
			break;
		}
		}
	}

	class DownLoadThread extends Thread {
		private String mUrl;

		public DownLoadThread(String url) {
			// TODO Auto-generated constructor stub
			mUrl = url;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (User.stuId == null || User.stuId.equals("null")
					|| User.stuId.equals("")) {
				Message msg = mHandler.obtainMessage();
				msg.what = DOWNLOAD_FAILURE;
				mHandler.sendMessage(msg);
				return;
			}
			Bitmap bitmap;
			String PHOTO_FILE_NAME;
			File tempFile;
			File f = Utils.getHelperFile();
			if (Utils.hasSdcard()&&headName!=null&&!headName.equals("")&&!headName.equals("null")) {

				PHOTO_FILE_NAME = headName;
				tempFile = new File(f, PHOTO_FILE_NAME);
				if (tempFile.exists()) {
					bitmap = BitmapFactory.decodeFile(tempFile.toString());
					User.head = bitmap;
					Message msg = mHandler.obtainMessage();
					msg.what = DOWNLOAD_SUCCESS;
					mHandler.sendMessage(msg);
					return;
				} else {
					bitmap = NetManager.getNetManager().getBitmap(mUrl);
					if (bitmap != null) {

						PHOTO_FILE_NAME = headName;
						Log.e("bitmap.toString="+bitmap.toString(),">>>>>>>>>>>>>>");
						tempFile = new File(f, PHOTO_FILE_NAME);
						if (Utils.save(tempFile.toString(), bitmap)) {
							SharedPreferences sp = getSharedPreferences(
									Table.CommentUserInf, Context.MODE_PRIVATE);
							Editor editor = sp.edit();
							editor.putString(Table.headHeadImageName,
									headName);
							editor.commit();
							User.head = bitmap;
							Message msg = mHandler.obtainMessage();
							msg.what = DOWNLOAD_SUCCESS;
							mHandler.sendMessage(msg);
							return;
						}
					}
				}

			} else {
				Log.e("sd卡不可用", "..............................");
			}
			Message msg = mHandler.obtainMessage();
			msg.what = DOWNLOAD_FAILURE;
			mHandler.sendMessage(msg);
			super.run();
		}
	}

	class LoginThread extends Thread {
		private String mUrl;
		private List<NameValuePair> mParams;

		public LoginThread(String url, List<NameValuePair> params) {
			// TODO Auto-generated constructor stub
			mUrl = url;
			mParams = params;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			String context = NetManager.getNetManager().getWebWithPost(mUrl,
					mParams);
			if (context != null) {
				
				Log.e("contenxt(" + LoginActivity.this.getClass().toString()
						+ ")=", context);
				try {
					JSONObject jsonObject = new JSONObject(context);
					headName = jsonObject.getString(Table.ImgUrl);
					if (headName.length() > 10) {
						headName=headName.substring(
								headName.lastIndexOf("/") + 1,
								headName.length());
						Log.e("headName="+ headName, ">>>>>>>>>>");
						SharedPreferences sp = getSharedPreferences(
								Table.CommentUserInf, Context.MODE_PRIVATE);
						Editor editor = sp.edit();
						editor.putString(Table.headHeadImageName,headName);
						editor.commit();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

				Message msg = mHandler.obtainMessage();
				msg.obj = context;
				msg.what = GET_CONTENT_SUCCESS;
				mHandler.sendMessage(msg);
			}

			else {
				Log.e("context=", "null");
				Message msg = mHandler.obtainMessage();
				msg.what = GET_CONTENT_FAILURE;
				mHandler.sendMessage(msg);
			}

			super.run();
		}
	}

	/**
	 * JSON解析
	 * 
	 * @param JSONString
	 * @return
	 */
	public static Map<String, String> parseJSONString(String JSONString) {
		Log.e("parseJSONString", "parseJSONString");
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			JSONObject person = new JSONObject(JSONString);
			// resultMap.put(Table.id, person.getString(Table.id));

			resultMap.put(Table.stuId, person.getString(Table.stuId));
			resultMap.put(Table.name, person.getString(Table.name));
			resultMap.put(Table.password, person.getString(Table.password));
			resultMap.put(Table.sex, person.getString(Table.sex));
			resultMap.put(Table.qq, person.getString(Table.qq));
			resultMap.put(Table.phone, person.getString(Table.phone));
			resultMap.put(Table.sendStart, person.getString(Table.sendStart));
			resultMap.put(Table.acceptStart,
					person.getString(Table.acceptStart));
			resultMap.put(Table.ImgUrl, person.getString(Table.ImgUrl));
			resultMap.put(Table.originPassword,
					person.getString(Table.originPassword));

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return resultMap;
	}

}
